<template>
  <div class="user">
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card class="box-card">
    <el-row :gutter="20">
      <el-col :span="8">
        <el-input
        clearable
        @clear="getUserList"
        v-model="queryDate.query"
        placeholder="请输入内容" class="input-with-select">
          <el-button slot="append" icon="el-icon-search"></el-button>
        </el-input>
      </el-col>
      <el-col :span="4">
        <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
      </el-col>
    </el-row>
  </el-card>
    <!-- 用户列表区域 -->
    <el-table :data="userList" border stripe>
      <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态" prop="mg_state">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="switchChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-button @click="editUser(scope.row.id)" type="primary" icon="el-icon-edit" size="mini"></el-button>
            <el-button @click="removeUser(scope.row.id)" type="danger" icon="el-icon-delete" size="mini"></el-button>
            <el-tooltip :enterable="false" class="item" effect="dark" content="Top Right 分配角色" placement="top-start">
              <el-button @click="showSetRoleDialog(scope.row)" type="warning" icon="el-icon-setting" size="mini"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
    </el-table>
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="resetAddForm">
    <!-- 对话框主体区域 -->
    <el-form :model="addForm" :rules="addUserFormRules" ref="addForm" label-width="70px">
        <el-form-item label="用户名" prop="username">
            <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
            <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
    </el-form>
    <!-- 对话框底部区域 -->
    <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
    </span>
</el-dialog>
    <!-- 用户分页区域 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page.sync="queryDate.pagenum"
      :page-size="queryDate.pagesize" :page-sizes="[1, 2, 5, 10]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
    <!-- // 编辑对话框 -->
    <el-dialog
        title="提示"
        :visible.sync="editDialogVisible"
        width="30%" @close="editDialogClosed">
        <!-- 对话框主体区域 -->
          <el-form :rules="editFormRules" :model="editUserInfo" ref="editFormRef" label-width="70px">
              <el-form-item label="用户名">
                  <el-input v-model="editUserInfo.username" disabled></el-input>
              </el-form-item>
              <el-form-item label="邮箱" prop="email">
                  <el-input v-model="editUserInfo.email"></el-input>
              </el-form-item>
              <el-form-item label="电话" prop="mobile">
                  <el-input v-model="editUserInfo.mobile"></el-input>
              </el-form-item>
          </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUserSubmit">确 定</el-button>
        </span>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="setRoleDialogVisible"
      width="50%">
      <div>
        <p>当前的用户：{{ userInfo.username }}</p>
        <p>当前的角色：{{ userInfo.role_name }}</p>
      </div>
      选择新角色：
      <div>
        <el-select v-model="selectValue" placeholder="请选择">
          <el-option
            v-for="item in rolesList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id">
          </el-option>
        </el-select>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRoleSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data () {
    // 验证邮箱规则
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/
      if (regEmail.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的邮箱'))
    }
    // 验证手机号码
    var checkMobile = (rule, value, cb) => {
      const regMobile = /^(((13[0-9])|(14[5-7])|(15[0-9])|(17[0-9])|(18[0-9]))+\d{8})$/
      if (regMobile.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的手机号码'))
    }
    return {
      // 获取用户列表的参数对象
      queryDate: {
        query: '',
        pagenum: 1,
        pagesize: 5
      },
      userList: [],
      total: 0,
      addDialogVisible: false,
      editDialogVisible: false,
      addForm: {
        username: '坐享云端之巅，笑看人生百态',
        email: '123456@qq.cc',
        password: '123456',
        mobile: '13123456789'
      },
      addUserFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 30, message: '长度在2-8位字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入用密码', trigger: 'blur' },
          { min: 2, max: 8, message: '长度在2-8位字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      editUserInfo: {},
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      setRoleDialogVisible: false,
      userInfo: '',
      rolesList: [],
      selectValue: ''
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    async getUserList () {
      const { data: res } = await this.$axios.get('users', { params: this.queryDate })
      if (res.meta.status !== 200) {
        return this.$Message.error('获取用户列表失败')
      }
      this.userList = res.data.users
      this.total = res.data.total
      // console.log(res)
    },
    // 监听pagesize 改变事件
    handleSizeChange (newSize) {
      this.queryDate.pagesize = newSize
      this.getUserList()
    },
    // 监听页码值的改变事件
    handleCurrentChange (newPage) {
      this.queryDate.pagenum = newPage
      this.getUserList()
    },
    // 监听switch 开关状态的改变事件
    async switchChange (row) {
      const { data: res } = await this.$axios.put(`users/${row.id}/state/${row.mg_state}`)
      if (res.meta.status !== 200) {
        console.log(res)
        row.mg_state = !row.mg_state
        return this.$message.error('更新状态失败')
      }
      this.$message.success('更新用户状态成功')
    },
    resetAddForm () {
      this.$refs.addForm.resetFields()
    },
    addUser () {
      this.$refs.addForm.validate(async flag => {
        if (!flag) return
        const { data: res } = await this.$axios.post('users', this.addForm)
        if (res.meta.status !== 201) return this.$message.error('创建用户失败')
        this.$message.success('创建用户成功')
        this.addDialogVisible = false
        this.getUserList()
      })
    },
    async editUser (id) {
      this.editDialogVisible = true
      const { data: res } = await this.$axios.get('users/' + id)
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('获取数据失败')
      this.editUserInfo = res.data
    },
    editDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },
    editUserSubmit () {
      this.$refs.editFormRef.validate(async flag => {
        console.log(123)
        if (!flag) return
        const { data: res } = await this.$axios.put('users/' + this.editUserInfo.id, {
          email: this.editUserInfo.email,
          mobile: this.editUserInfo.mobile
        })
        if (res.meta.status !== 200) return this.$message.error('编辑用户失败')
        this.editDialogVisible = false
        this.getUserList()
        this.$message.success('编辑用户成功')
      })
    },
    removeUser () {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 点击分配角色
    async showSetRoleDialog (userInfo) {
      this.userInfo = userInfo
      const { data: res } = await this.$axios.get('roles')
      // 获取到数据 控制台
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error('获取数据失败')
      this.rolesList = res.data
      this.setRoleDialogVisible = true
    },
    // 分配角色
    async setRoleSubmit () {
      if (!this.selectValue) return this.$message.error('亲，请选择角色哦！')
      const { data: res } = await this.$axios.put(`users/${this.userInfo.id}/role`, {
        rid: this.selectValue
      })
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('角色分配失败!')
      this.$message.success('@角色分配成功')
      this.setRoleDialogVisible = false
      this.getUserList()
    }
  }
}
</script>
<style lang="less" scoped>
</style>
